<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use App\Model\AdminLogsModel;
use App\Model\AdminRolesModel;
use App\Model\AdminRoleUserModel;

//管理员表
class AdminUserModel extends Model
{
    //定义一个表名
    protected $table = 'admin_users';
    //定义主键
    protected $primaryKey = 'id';

    //状态
    public function getStateAttribute($value) {
        $arr = ['0'=>'禁用','1'=>'启用'];
        return ['msg'=>$arr[$value],'value'=>$value];
    }

    //关联角色
    public function roles()
    {
        return $this->belongsToMany(AdminRolesModel::class,'admin_role_user','user_id','role_id');
    }

    //启用禁用
    public function updateState($id,$state)
    {
        $res = $this->find($id);
        if($state == 1){
            $msg = '更改管理员【'.$res['user'].'】(id:'.$res['id'].')状态为【启用】';
        }
        if($state == 0){
            $msg = '更改管理员【'.$res['user'].'】(id:'.$res['id'].')状态为【禁用】';
        }

        $arr = $this->where("id",$id)->update(['state' => $state]);
        if($arr){
            //添加日志
            AdminLogsModel::addLog($msg);
            $returnArr['code'] = 1;
            $returnArr['msg'] = "修改成功";
        }else{
            $returnArr['code'] = 2;
            $returnArr['msg'] = "修改失败";
        }
        return $returnArr;
    }

    //删除
    public function delId($id)
    {
        $res = $this->find($id);
        if($res){
            if($this->where('id', $id)->delete()){
                //删除该管理员-角色
                $aruModel = new AdminRoleUserModel;
                $aruModel->where('user_id',$id)->delete();
                //添加日志
                $msg = "删除管理员【".$res['user']."】(id:".$res['id'].")";
                AdminLogsModel::addLog($msg);
                $returnArr['code'] = 1;
                $returnArr['msg'] = "删除成功";
            }else{
                $returnArr['code'] = 2;
                $returnArr['msg'] = "删除失败";
            }
        }else{
            $returnArr['code'] = 3;
            $returnArr['msg'] = "未找到指定数据或已删除";
        }
        return $returnArr;
    }

    /*
    // 更新管理员状态
    public function updateState($id) {
        $user = $this->find($id);
        if($user['state']['value'] == 1){
            $state = '0';
            $msg = '【禁用】管理员【'.$user['user'].'】';
        }elseif($user['state']['value'] == 0){
            $state = '1';
            $msg = '【启用】管理员【'.$user['user'].'】';
        }
        // 添加日志
        AdminLogsModel::addLog($msg);
        return $user->where('id', $id)->update(['state' => $state]);
    }

    public function deleteAdmin($id) {
        $user = $this->find($id);
        // 添加日志
        AdminLogsModel::addLog('删除管理员【'.$user['user'].'】');
        return $this->where('id', $id)->delete();
    }
    */
    
}
